package com.duowei.diandan.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.duowei.diandan.app.InitManager;

public class TouchService extends Service implements View.OnTouchListener {
    private static final String TAG = "TouchService";

    private WindowManager mWindowManager;
    private LinearLayout mDummyView;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");

        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        mDummyView = new LinearLayout(this);

        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(1, LinearLayout.LayoutParams.MATCH_PARENT);
        mDummyView.setLayoutParams(llp);
        mDummyView.setOnTouchListener(this);

        WindowManager.LayoutParams wlp;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            wlp = new WindowManager.LayoutParams(
                    1,
                    1,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                    PixelFormat.TRANSPARENT);
        } else {
            wlp = new WindowManager.LayoutParams(
                    1,
                    1,
                    WindowManager.LayoutParams.TYPE_PHONE,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                    PixelFormat.TRANSPARENT);
        }
        wlp.gravity = Gravity.START | Gravity.TOP;
        mWindowManager.addView(mDummyView, wlp);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");

        if (mWindowManager != null) {
            if (mDummyView != null) {
                mWindowManager.removeView(mDummyView);
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
//        Log.d(TAG, "onTouch: " + v);
        InitManager.getInstance().setRestTouchTime();

        return false;
    }
}
